import pandas as pd

import requests
from requests import get
from concurrent.futures import ThreadPoolExecutor
from base.base import Base
import json

tokenauthorization='Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJlYjVhMWFkZDA4ZjU0ZWExOTU4NGQ5MjJjNjIyNzU0YSIsImF1ZCI6ImlvdGNpdHkiLCJpc3MiOiJvYXV0aCIsInJuZCI6InA0MDNoaTZnIiwiZXhwIjoxNzM0MDgyOTc1LCJpYXQiOjE3MzM0NzgxMTV9.8ZMzSLHfGXB-fRZ0tR4X0GdI_ud-zBYsupxS0EuWbOg'

base=Base()
param_type='application/json'
headers={
    'tenantid':'T0002',
    'tokenauthorization':tokenauthorization
}
data={
    "draw": 1,
    "length": 999,
    "start": 0,
    "jsonParam": "{\"device_status\":\"\",\"product_key\":\"media\",\"device_name\":\"2号楼\",\"device_unique_no\":\"\"}"
}
url='http://117.187.242.207:8082/gateway/twiot-device-server/device/pageList.json'
res=json.loads(base.send_post(url,param_type,headers=headers,data=data))['result']['data']
flv_list=[]
# print(res)
for dev in res:
    param_type='application/json'
    headers={
    'tenantid':'T0002',
    'tokenauthorization':tokenauthorization
    }
    url='http://117.187.242.207:8082/gateway/twiot-exts-gazrdata/api/video/getUrl?productKey=media&deviceName='+dev['device_name']
    res=base.send_get(url,param_type,headers=headers)
    flv=json.loads(res)['result']['flv']
    device_desc=dev['device_desc']
    flv_list.append([device_desc,flv])
print(flv_list)

# 定义并发请求的函数
def check_device_stream(device_info):
    device_name, url = device_info
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            chunk = next(response.iter_content(chunk_size=1024), None)
            if chunk:
                print(f"{device_name} 成功获取流数据")
                return device_name  # 返回设备名称
        else:
            print(f"{device_name} 请求失败，状态码: {response.status_code}")
    except Exception as e:
        print(f"{device_name} 请求异常: {e}")

# 使用 ThreadPoolExecutor 并发请求
with ThreadPoolExecutor(max_workers=20) as executor:
    results = list(executor.map(check_device_stream, flv_list))

# 过滤出成功请求的设备名称
successful_devices = [device for device in results if device]

# 将成功获取数据的设备名称保存到 Excel 文件
df = pd.DataFrame(successful_devices, columns=["设备名称"])
df.to_excel("successful_devices3.xlsx", index=False)

